package com.bt.mes.brm.provider.service;

import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_ADD;
import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_CANCEL;
import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_DELETE;
import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_QUERY;
import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_UPDATE;
import static com.bt.mes.common.bean.def.GenericDef.E_XPBMDLDF_NOT_FOUND_MDL;
import static com.bt.mes.common.bean.def.GenericDef.RETURN_CODE_OK;
import static com.bt.mes.common.bean.def.GenericDef.RETURN_CODE_UNKNOWN;
import static com.bt.mes.common.bean.def.GenericDef.RETURN_MESG_OK;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.bt.mes.brm.api.service.IXpbmdldfService;
import com.bt.mes.brm.provider.tx.Xpbistol.XpbistolI;
import com.bt.mes.brm.provider.tx.Xpbmdldf.XpbmdldfI;
import com.bt.mes.brm.provider.tx.Xpbmdldf.XpbmdldfIA;
import com.bt.mes.brm.provider.tx.Xpbmdldf.XpbmdldfO;
import com.bt.mes.brm.provider.tx.Xpbmdldf.XpbmdldfOA;
import com.bt.mes.common.dao.IBisBomDao;
import com.bt.mes.common.dao.IBisMdlDefDao;
import com.bt.mes.common.util.JacksonUtil;
import com.bt.mes.common.util.MqOpe;
import com.bt.table.ppt.Bis_bom;
import com.bt.table.ppt.Bis_mdl_def;

@Service("xpbmdldfService")
public class XpbmdldfService implements IXpbmdldfService {
	private Logger logger = Logger.getLogger(XpbmdldfService.class);
	private XpbmdldfI inTrx;
	private XpbmdldfO outTrx;

	@Autowired
	private IBisMdlDefDao bisMdlDefDao;

	@Autowired
	private IBisBomDao bisBomDao;

	public String subMainProc(String strInMsg) {
		logger.info("InTrx is " + strInMsg);
		Session session = bisMdlDefDao.getCrSession();
		String strOutTrx = null;
		try {
			inTrx = new XpbmdldfI();
			outTrx = new XpbmdldfO();

			outTrx.setTrx_id("XPBMDLDF");
			outTrx.setType_id("O");

			inTrx = JacksonUtil.fromJson(strInMsg, XpbmdldfI.class);
			char action_flg = inTrx.getAction_flg().charAt(0);
			switch (action_flg) {
			case ACTION_FLG_QUERY:
				queryByCondition();
				break;
			case ACTION_FLG_ADD:
				addFnc();
				break;
			case ACTION_FLG_UPDATE:
				updateFnc();
				break;
			case ACTION_FLG_DELETE:
				deleteFnc();
				break;
			case ACTION_FLG_CANCEL:
				findMdlbycus();
				break;
			default:
				errActionFnc();
			}
			if (RETURN_CODE_OK.equals(outTrx.getRtn_code())) {
				session.flush();
			} else {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		} catch (Exception ex) {
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			outTrx.setRtn_mesg(ex.toString());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		} finally {
			strOutTrx = JacksonUtil.toJSONStr(outTrx);
			logger.info(strOutTrx);
		}
		return strOutTrx;
	}

	public void addFnc() {
		XpbmdldfIA iary = inTrx.getIary().get(0);

		StringBuffer rsvInfoBuffer = new StringBuffer();
		// check exit

		Bis_mdl_def bismdl = bisMdlDefDao.get(iary.getMdl_id());

		if (bismdl != null) {
			outTrx.setRtn_code("301234");
			outTrx.setRtn_mesg("[" + iary.getMdl_id() + "]已经存在!,重复的记录");
		} else {
			//
			Bis_mdl_def bisMdlDef = new Bis_mdl_def();
			bisMdlDef.setMdl_id(iary.getMdl_id());
			bisMdlDef.setMdl_cate(iary.getMdl_cate());
			bisMdlDef.setMdl_code(iary.getMdl_code());
			if (iary.getMdl_d_weight() != null) {
				bisMdlDef.setMdl_d_weight(Double.valueOf(iary.getMdl_d_weight()));
			}
			bisMdlDef.setMdl_dsc(iary.getMdl_dsc());
			bisMdlDef.setMdl_ec_code(iary.getMdl_ec_code());
			bisMdlDef.setMdl_param(iary.getMdl_param());
			bisMdlDef.setMdl_size(iary.getMdl_size());
			bisMdlDef.setMdl_sub_id(iary.getMdl_sub_id());

			rsvInfoBuffer.append(iary.getDqr_mdl_typ_flg());
			rsvInfoBuffer.append(iary.getDqr_layout_id_flg());
			rsvInfoBuffer.append(iary.getDqr_from_thickness_flg());
			bisMdlDef.setMdl_typ(iary.getMdl_typ());
			bisMdlDef.setLayot_id_fk(iary.getLayot_id_fk());

			if (iary.getMdl_u_weight() != null) {
				bisMdlDef.setMdl_u_weight(Double.valueOf(iary.getMdl_u_weight()));
			}
			bisMdlDef.setBox_cnt(iary.getBox_cnt());
			bisMdlDef.setCus_fab_id(iary.getCus_fab_id());
			bisMdlDef.setCus_mdl_id(iary.getCus_mdl_id());
			bisMdlDef.setFrom_thickness(iary.getFrom_thickness());
			bisMdlDef.setLayot_id_fk(iary.getLayot_id_fk());
			bisMdlDef.setOk_ratio(iary.getOk_ratio());
			bisMdlDef.setPath_id_fk(iary.getPath_id_fk());
			bisMdlDef.setPath_ver_fk(iary.getPath_ver_fk());
			bisMdlDef.setRsv_info(iary.getRsv_info());
			bisMdlDef.setSwh_time(iary.getSwh_time());
			bisMdlDef.setTo_thickness(iary.getTo_thickness());
			bisMdlDef.setRsv_info(rsvInfoBuffer.toString());
			bisMdlDef.setCus_id(iary.getCus_id());
			bisMdlDefDao.save(bisMdlDef);

			outTrx.setRtn_code(RETURN_CODE_OK);
			outTrx.setRtn_mesg(RETURN_MESG_OK);
		}
	}

	public void updateFnc() {
		XpbmdldfIA iary = inTrx.getIary().get(0);
		String mdlId = iary.getMdl_id();

		Bis_mdl_def bisMdlDef = bisMdlDefDao.get(mdlId);
		if (bisMdlDef == null) {
			outTrx.setRtn_code(E_XPBMDLDF_NOT_FOUND_MDL + "");
			outTrx.setRtn_mesg("not Found Record[BIS_MDL_DEF]");
		}

		if (iary.getMdl_dsc() != null) {
			bisMdlDef.setMdl_dsc(iary.getMdl_dsc());
		}
		if (iary.getMdl_cate() != null) {
			bisMdlDef.setMdl_cate(iary.getMdl_cate());
		}

		StringBuffer rsvInfoBuffer = new StringBuffer();
		rsvInfoBuffer.append(iary.getDqr_mdl_typ_flg());
		rsvInfoBuffer.append(iary.getDqr_layout_id_flg());
		rsvInfoBuffer.append(iary.getDqr_from_thickness_flg());

		bisMdlDef.setMdl_typ(iary.getMdl_typ());
		bisMdlDef.setLayot_id_fk(iary.getLayot_id_fk());

		if (iary.getMdl_size() != null) {
			bisMdlDef.setMdl_size(iary.getMdl_size());
		}
		if (iary.getMdl_ec_code() != null) {
			bisMdlDef.setMdl_ec_code(iary.getMdl_ec_code());
		}
		if (iary.getMdl_code() != null) {
			bisMdlDef.setMdl_code(iary.getMdl_code());
		}
		if (iary.getMdl_param() != null) {
			bisMdlDef.setMdl_param(iary.getMdl_param());
		}
		if (iary.getLayot_id_fk() != null) {
			bisMdlDef.setLayot_id_fk(iary.getLayot_id_fk());
		}
		if (iary.getPath_id_fk() != null) {
			bisMdlDef.setPath_id_fk(iary.getPath_id_fk());
		}
		if (iary.getPath_ver_fk() != null) {
			bisMdlDef.setPath_ver_fk(iary.getPath_ver_fk());
		}
		if (iary.getMdl_d_weight() != null) {
			bisMdlDef.setMdl_d_weight(Double.valueOf(iary.getMdl_d_weight()));
		}
		if (iary.getMdl_u_weight() != null) {
			bisMdlDef.setMdl_u_weight(Double.valueOf(iary.getMdl_u_weight()));
		}
		// if(iary.getMdl_sub_id()!=null){
		// bisMdlDef.setMdl_sub_id(iary.getMdl_sub_id());
		// }

		if (iary.getBox_cnt() != null) {
			bisMdlDef.setBox_cnt(iary.getBox_cnt());
		}
		if (iary.getCus_mdl_id() != null) {
			bisMdlDef.setCus_mdl_id(iary.getCus_mdl_id());
		}
		if (iary.getCus_fab_id() != null) {
			bisMdlDef.setCus_fab_id(iary.getCus_fab_id());
		}
		if (iary.getVcr_flg() != null) {
			bisMdlDef.setVcr_flg(iary.getVcr_flg());
		}
		if (iary.getOk_ratio() != null) {
			bisMdlDef.setOk_ratio(iary.getOk_ratio());
		}
		if (iary.getFrom_thickness() != null) {
			bisMdlDef.setFrom_thickness(iary.getFrom_thickness());
		}
		if (iary.getTo_thickness() != null) {
			bisMdlDef.setTo_thickness(iary.getTo_thickness());
		}
		if (iary.getSwh_time() != null) {
			bisMdlDef.setSwh_time(iary.getSwh_time());
		}
		if (iary.getValid_flg() != null) {
			bisMdlDef.setValid_flg(iary.getValid_flg());
		}
		if (iary.getRsv_info() != null) {
			bisMdlDef.setRsv_info(iary.getRsv_info());
		}
		if (iary.getCus_id() != null) {
			bisMdlDef.setCus_id(iary.getCus_id());
		}
		bisMdlDef.setRsv_info(rsvInfoBuffer.toString());

		bisMdlDefDao.update(bisMdlDef);

		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void deleteFnc() {
		XpbmdldfIA iary = inTrx.getIary().get(0);
		String mdlId = iary.getMdl_id();

		Bis_mdl_def bisMdlDef = bisMdlDefDao.get(mdlId);
		if (bisMdlDef == null) {
			outTrx.setRtn_code(E_XPBMDLDF_NOT_FOUND_MDL + "");
			outTrx.setRtn_mesg("not Found Record[BIS_MDL_DEF]");
		}
		bisMdlDefDao.delete(bisMdlDef);

		String hql = "FROM Bis_bom where mdl_id_fk=?";
		List<Bis_bom> bisBomList = bisBomDao.list(hql, mdlId);
		for (Bis_bom bis_bom : bisBomList) {
			bisBomDao.delete(bis_bom);
		}

		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void queryByCondition() {
		/***
		 * 暂支持两种查询: 1.by mdl_id 查询 2.by mdl_id 模糊查询 3.空 查询所有
		 **/
		StringBuffer buffer = new StringBuffer();
		XpbmdldfIA iary = inTrx.getIary().get(0);
		String mdlId = iary.getMdl_id();
		String cusId = iary.getCus_id();
		String sql = "";
		String mdlHql = "";
		List<XpbmdldfOA> oaryList = new ArrayList<XpbmdldfOA>();

		sql = "SELECT * FROM BIS_MDL_DEF where 1=1 ";

		if (mdlId != null) {
			if (mdlId.indexOf("*") == -1) {// 如果不包含*,精确查询
				sql = sql + "and MDL_ID='" + mdlId + "'";
			} else {// 模糊查询
				sql = sql + "and MDL_ID like '" + mdlId.replace("*", "%") + "'";
			}
		}
		if (cusId != null) {
			sql = sql + " and MDL_ID IN ( select MDL_ID_FK FROM BIS_BOM WHERE MTRL_PROD_ID_FK IN ("
					+ " SELECT EXT_1 FROM BIS_DATA WHERE DATA_CATE = 'CSMT' AND DATA_ITEM ='" + cusId + "'))";
		}
		@SuppressWarnings("unchecked")
		List<Bis_mdl_def> bisMdlDefList = bisMdlDefDao.findBySQL(sql, Bis_mdl_def.class);

		for (Bis_mdl_def bisMdlDef : bisMdlDefList) {
			XpbmdldfOA oary = new XpbmdldfOA();
			oary.setMdl_id(bisMdlDef.getMdl_id());
			oary.setMdl_cate(bisMdlDef.getMdl_cate());
			oary.setMdl_code(bisMdlDef.getMdl_code());
			if (bisMdlDef.getMdl_d_weight() != null) {
				oary.setMdl_d_weight(bisMdlDef.getMdl_d_weight().toString());
			}
			oary.setMdl_dsc(bisMdlDef.getMdl_dsc());
			oary.setMdl_ec_code(bisMdlDef.getMdl_ec_code());
			oary.setMdl_param(bisMdlDef.getMdl_param());
			oary.setMdl_size(bisMdlDef.getMdl_size());
			oary.setMdl_sub_id(bisMdlDef.getMdl_sub_id());
			oary.setMdl_typ(bisMdlDef.getMdl_typ());
			if (bisMdlDef.getMdl_u_weight() != null) {
				oary.setMdl_u_weight(bisMdlDef.getMdl_u_weight().toString());
			}
			oary.setBox_cnt(bisMdlDef.getBox_cnt());
			oary.setCus_id(bisMdlDef.getCus_id());
			oary.setCus_fab_id(bisMdlDef.getCus_fab_id());
			oary.setCus_mdl_id(bisMdlDef.getCus_mdl_id());
			if (bisMdlDef.getFrom_thickness() != null) {
				oary.setFrom_thickness(bisMdlDef.getFrom_thickness());
			}

			oary.setLayot_id_fk(bisMdlDef.getLayot_id_fk());
			oary.setOk_ratio(bisMdlDef.getOk_ratio());
			oary.setPath_id_fk(bisMdlDef.getPath_id_fk());
			oary.setPath_ver_fk(bisMdlDef.getPath_ver_fk());

			String rsvInfo = bisMdlDef.getRsv_info();
			oary.setDqr_flg(!StringUtils.isEmpty(rsvInfo) && rsvInfo.contains("Y") ? "Y" : "N");
			if (!StringUtils.isEmpty(rsvInfo) && rsvInfo.length() >= 3) {
				oary.setDqr_mdl_typ_flg(rsvInfo.substring(0, 1));
				oary.setDqr_layout_id_flg(rsvInfo.substring(1, 2));
				oary.setDqr_from_thickness_flg(rsvInfo.substring(2, 3));
			}
			oary.setRsv_info(rsvInfo);

			oary.setSwh_time(bisMdlDef.getSwh_time());
			oary.setTo_thickness(bisMdlDef.getTo_thickness());
			oary.setValid_flg(bisMdlDef.getValid_flg());
			oary.setVcr_flg(bisMdlDef.getVcr_flg());
			oaryList.add(oary);
		}
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());

		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg("success");
	}

	public void errActionFnc() {
		outTrx.setRtn_code("0000009");
		outTrx.setRtn_mesg("Invalid Action_flg");
	}

	public void findMdlbycus() {

		XpbmdldfIA iary = inTrx.getIary().get(0);
		String cusId = iary.getCus_id();
		String sql = "";
		List<XpbmdldfOA> oaryList = new ArrayList<XpbmdldfOA>();

		sql = "SELECT A.* FROM BIS_BOM A JOIN BIS_DATA B ON A.MTRL_PROD_ID_FK=B.EXT_1 WHERE "
				+ "B.DATA_CATE = 'CSMT' AND B.DATA_ITEM ='" + cusId + "'";

		List<Bis_bom> bisbomList = bisBomDao.findBySQL(sql, Bis_bom.class);

		for (Bis_bom bis_bom : bisbomList) {
			XpbmdldfOA oary = new XpbmdldfOA();
			oary.setMdl_id(bis_bom.getId().getMdl_id_fk());
			oaryList.add(oary);
		}
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());

		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg("success");
	}
}
